<template>
	<div class="category" v-if="selectedCategories.length>0">
		<div v-for="(level, index) in selectedCategories" :key="index" class="category-level">
			<div class="category-label" lass="category-label">{{ selectLevels[index]?.label }}</div>
			<div class="category-list">
				<div v-for="category in level" :key="category.id"
					:class="['category-item', { active: isSelected(category, index) }]"
					@click="selectCategory(category, index)">
					{{ category.name }}
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from 'vue'
	import sheep from '@/sheep'

	// 定义组件的props
	const props = defineProps({
		isTk: {
			type: Boolean,
			default: false
		},
		content_type: {
			type: String,
			default: ''
		}
	});

	// 定义emit
	const emit = defineEmits(['update:selected'])

	const currentYear = new Date().getFullYear()
	//let years = [{name: '全部'}, {id: currentYear, name: `${currentYear}`}, {id: currentYear - 1, name: `${currentYear - 1}`}]
	let years = [{
		name: '全部'
	}]
	const categoryLabels = [{
		label: '项目',
		field: 'category1'
	}, {
		label: '科目',
		field: 'category2'
	}];
	const yearsLabel = {
		label: '年份',
		field: 'year'
	}
	const tikuTypeLabel = {
		label: '类型',
		field: 'tikutype'
	}

	function addAllChildrenItem(item, lastLevel) {
		return {
			id: item.id,
			name: item.name,
			children: item.children?.length ? [{
					name: '全部',
					children: [...lastLevel]
				},
				...item.children.map(child => addAllChildrenItem(child, lastLevel))
			] : [...lastLevel]
		}
	}

	// 存储每一层选中的分类
	const selection = ref([]);
	const categories = ref([]);
	onMounted(() => {
		if (props.isTk) {
			sheep.$api.course.getCourseCategoryWithTK().then((res) => {
				const cates = res.data.categories.children;
				let tikuTypes = res.data.tikutype.map(item => ({
					id: item,
					name: item
				}));
				tikuTypes = [{
					name: '全部'
				}, ...tikuTypes];
				categories.value = cates.map(item => addAllChildrenItem(item, tikuTypes));
				selectCategory(categories.value[0], 0);
			});
		} else {
			sheep.$api.course.getUserCategory({
				'content_type': props.content_type
			}).then((res) => {
				var tempyears = res.data.years
				// 第一步：获取对象的所有键，并转换为数字数组
				const keys = Object.keys(tempyears).map(Number);
				// 第二步：根据这些键，从对象中检索出对应的年份值
				const years_temp = keys.map(key => tempyears[key]);
				// 第三步：对年份数组进行倒序排序
				const sortedYearsDesc = years_temp.sort((a, b) => b - a);
				if (sortedYearsDesc.length > 0) {
					for (var i = 0; i < sortedYearsDesc.length; i++) {
						let yy = {
							id: parseInt(sortedYearsDesc[i]),
							name: sortedYearsDesc[i]
						}
						years.push(yy)
					}
				}

				if (props.content_type == 'tiku') {
					let tikuTypes = res.data.tikutype.map(item => ({
						id: item,
						name: item
					}));
					tikuTypes = [{
						name: '全部'
					}, ...tikuTypes];
					categories.value = res.data.children.map(item => addAllChildrenItem(item, tikuTypes));
				} else {
					categories.value = res.data.children.map(item => addAllChildrenItem(item, years));
				}
				selectCategory(categories.value[0], 0);
			});
		}
	});

	// 每次选中一个元素后，重新计算其所有子层级的元素
	const selectCategory = (category, level) => {
		// 清除当前层级后的所有选择
		selection.value = selection.value.slice(0, level)
		// 添加新的选择
		selection.value.push(category)

		// 自动选择子层级的第一个选项
		let current = category;
		while (current.children?.length) {
			current = current.children[0];
			selection.value.push(current);
		}

		const selected = selection.value.map((item, index) => ({
			id: item.id,
			field: selectLevels.value[index].field
		}));
		const result = selected.reduce((acc, item) => {
			if (item.id) {
				acc[item.field] = item.id;
			}
			return acc;
		}, {});
		emit('update:selected', result);
	}

	// 计算当前要显示的所有层级的分类
	const selectedCategories = computed(() => {
		const result = [categories.value]
		selection.value.forEach(item => {
			if (item.children?.length) {
				result.push(item.children)
			}
		});

		return result;
	});

	const selectLevels = computed(() => {
		if (props.isTk) {
			return [...categoryLabels.slice(0, selection.value.length - 1), tikuTypeLabel];
		}
		if (props.content_type == "tiku") {
			return [...categoryLabels.slice(0, selection.value.length - 1), tikuTypeLabel];
		}
		return [...categoryLabels.slice(0, selection.value.length - 1), yearsLabel];
	});

	// 判断分类是否被选中
	const isSelected = (category, level) => {
		return selection.value[level]?.id === category.id
	}
</script>

<style scoped>
	.category {
		background-color: #fff;
		border-bottom: 1px solid #e5e5e5;
		padding-bottom: 15px;
		margin-top: 20px;
		margin-bottom: 20px;
	}

	.category-level {
		display: flex;
		gap: 1rem;
	}

	.category-label {
		width: 60px;
		flex-shrink: 0;
		padding: 6px 10px;
		font-size: 16px;
		line-height: 20px;
	}

	.category-list {
		display: flex;
		flex-wrap: wrap;
	}

	.category-item {
		padding: 6px 10px;
		margin-bottom: 10px;
		margin-right: 10px;
		border-radius: 4px;
		cursor: pointer;
		line-height: 20px;
	}

	.category-item:hover {
		background-color: #f5f5f5;
	}

	.category-item.active {
		background-color: var(--ui-BG-Main);
		color: white;
	}
</style>